# -*- encoding:utf8 -*-
import json
from django.utils import timezone
from attendance.tool_func import get_or_none
from attendance.models import LeaveApplication
from attendance.msg import send_msg
from attendance.convert import dt2str,t2i
from staff.models import StaffInfo
import django.dispatch
from ..leave_info import application_leave_span

# 申请单状态改变
application_changed = django.dispatch.Signal(providing_args=["staff", "date"])

def check_leave_app(leader_id,leave_id,check,note):
    """
    领导审批假期
    @leader_id :staffInfo对象， 领导
    """
    leave_app = get_or_none(LeaveApplication, id=leave_id)
    if leave_app:
        
        if _update_check_record(leave_app, leader_id, check, note)==0:
            return {'status':'fail','msg':'you have not permission to check the leave'}

        return {'status': 'success'} 

def get_checkLeader_list(category,staff,span=1):
    """
    某类型，某员工，需要审批的领导,
    【这个函数是易变的】
    Args:
    span:int ，申请的时间长度，以分钟数计算
    return ['AE1856','AE1856','hr']
    """
    out=[]
    if category in ['personal_leave']:
        if staff.func_leader:
            out.append(staff.func_leader.employee_id)
        elif staff.pro_leader:
            out.append(staff.pro_leader.employee_id)   
        if span>8*2*60:          # when personal_leave.span> 2 day ,need echo check
            out.append('AE1001') # echo   
    elif category in ['miss_check',]:
        if staff.func_leader:
            out.append(staff.func_leader.employee_id)
        out.append('hr')
    elif category.endswith('_import'):  # 导入假期，不需要审批
        out=[]
    else:
        if staff.func_leader:
            out.append(staff.func_leader.employee_id)
        elif staff.pro_leader:
            out.append(staff.pro_leader.employee_id)
    return out

def approve_leave_app(leave_app):
    """直接同意一个假期申请
    现在暂时用于测试
    """
    records = get_or_create_application_check_record(leave_app)
    for record in records:
        record['status']='approved'
    leave_app.check_record=json.dumps(records)
    leave_app.save()

def _update_check_record(leave_app,empid,status,note):
    """
    更新审批记录状态
    return: 1 表示更新了一个记录 ，0 表示此人不在领导列表中，所以没有更新任何记录
    """
    nowstr = dt2str(timezone.localtime(timezone.now()))
    leaders = json.loads(leave_app.check_record)
    for leader in leaders:
        if leader['empid']==empid:
            leader['status']=status
            leader['note']=note
            leader['utime']=nowstr
            leave_app.check_record=json.dumps(leaders)
            leave_app.save()
            return 1
    return 0

def get_or_create_application_check_record(leave_app):
    """return 审批领导列表
    [{'empid':xx,'status':'approve','note':xxx,}]
    """
    staff=leave_app.staff
    if not leave_app.check_record:
        stream=[{'empid':leader_id,'status':'pending'} for leader_id in \
                get_checkLeader_list(leave_app.category,staff,application_leave_span(leave_app))]
        leave_app.check_record=json.dumps(stream)
    else:
        stream=json.loads(leave_app.check_record)
    return stream


def notify_next_check_person(leave):
    """[{status:'pending',}]
    """
    leaders=get_or_create_application_check_record(leave)  
    title= '%s apply for %s' % (leave.staff.en_name, leave.category)    
    for whos in leaders:
        if whos['status']=='pending':
            leader=get_or_none(StaffInfo,employee_id=whos['empid'])
            if leader:
                send_msg(leader,category='check',title=title, content=leave.id)
            break
        # elif whos['status']=='rejected':
            # send_msg(leave.staff,title=title,content='%s rejected'%title)
            # break
        elif whos['status']=='revoked':
            break    

def compute_application_status(stream):
    """更新整条申请的状态
    """
    if all(map(lambda dot:dot['status']=='approved', stream)):
        return 'approved'
    elif any(map(lambda dot:dot['status']=='revoked', stream)):
        return 'revoked'
    elif any(map(lambda dot:dot['status']=='rejected', stream)):
        return 'rejected'
    elif any(map(lambda dot:dot['status']!='pending', stream)):
        return 'checking'
    elif all(map(lambda dot:dot['status']=='pending', stream)):
        return 'pending'    


